<!--
* description: 今日待分配线索(弹窗)
* author: mwh
* createdDate: 2010-11-21
-->
<template>
  <section class="dlrRule">
    <el-dialog v-dialogDrag
      title="线索分配"
      class="WorkGroup"
      :close-on-click-modal="false"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      @close="sendCode"
      width="600px"
    >
      <dialogHeader
        slot="title"
        :title="'线索分配'"
        :styleType="$store.state.app.dialogType"
      ></dialogHeader>
      <span style="color:red">共选择任务：{{serverOrderArray.length}}条，数量为0或为空表示不为此人分配</span>
      <one-table-template
        ref="multipleTable"
        :dynamicButtons="tableButtons"
        :dynamicComponents="tableComponents"
        :dynamicApiConfig="apiConfig"
        :dynamicTableCols="tableCols"
        :dynamicFormFields="formField"
        :dynamicIsShowSelect="isMul"
        :callbackObj="callbackObj"
        :dynamicIsInitTable="true"
      />
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from "@/components/mixins/formMixins";
//import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import { valueObjectMixins } from "@/components/mixins/valueObjectMixins";
import { crmApis } from "@/api/apiList/crm.js";
import { requestGraphQL } from "@/api/commonRequest";
import OneTableTemplate from "@/components/crm/commonComponents/crmPopupsOneTableFP";
export default {
  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [valueObjectMixins, formMixins],
  components: {
    OneTableTemplate,dialogHeader: () => import("@/components/dialogHeader") //弹窗标题
  },
  data() {
    return {
      isMul:{},
      redata: "",
      serverOrderArray: [], //主页面传递过来的单号数组
      usersAndNumber: [],
      curPopupsVisible: false,
      // 网格查询API配置对象
      apiConfig: crmApis.mdmOrgEmployeeQueryFindAll,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          clickEvent: () => this.averAssign(),
          text: "平均分配",
          position:"top"
        },
        {
          compKey: "btnKey2",
          type: "primary",
          size: "small",
          clickEvent: () => this.clueAssignSure(),
          text: "确认",
          position:"bottom"
        }
      ],
      // 动态组件-查询条件
      tableComponents: [
        // 显示组件
      ],
      // 动态生成网格列
      tableCols: [
        {
          prop: "empName",
          label: "人员",
          width: null,
          align: "center"
        },
        {
          prop: "userId",
          label: "用户ID",
          width: null,
          align: "center",
          hidden: true
        },
        {
          prop: "isEnable",
          label: "数量",
          width: 300,
          align: "center",
          isComponent: true,
          comps: [
            {
              compKey: "propKey1",
              width: 290,
              isMul: false,
              isShowLabel: false,
              codeField: "isEnable",
              component: () => import("@/components/crm/textbox/crmTextInput")
            }
          ]
        }
      ],
      //表单查询数据（查询条件）
      formField: {
       positionCode: "R_XSZX",
       isEnable: "1"
      },
      // 回调方法对象
      callbackObj: {
        // 查询成功后回调
        onQueryReturn: (response) => {
          this.onQueryReturn(response)
        }
      },
    };
  },
  updated() {
    this.$nextTick(() => {
      this.initQueryEmployeeInfo();
    });
  },
  methods: {
    // 查询成功后回调
    onQueryReturn(response) {
      this.outStoreTote = response.data[this.apiConfig.ServiceCode].records
      let sumMoney = 0
      let list = []
      list = response.data[this.apiConfig.ServiceCode].rows
      for (let i = 0; i < list.length; i++) {
        response.data[this.apiConfig.ServiceCode].rows[i].isEnable=""
      }
    },
    /**
     * @initQueryEmployeeInfo:人员初始化
     */
    initQueryEmployeeInfo: function() {
      let that = this;
      that.$refs.multipleTable.queryTable(1, "", "", "", function() {
        // setTimeout(function() {
        //   that.averAssign()
        // }, 400);
      });
    },

    /**
     * @averAssign：平均分配/电脑分配
     */
    averAssign: function() {
      let that = this;
      console.log(that.serverOrderArray);
      that.usersAndNumber = [];
      let selectionRowArray = this.$refs.multipleTable.$refs.multipleTable
        .selection; //选择行数组
      let serverOrderNum = that.serverOrderArray.length; //线索单号数量
      let userNum = this.$refs.multipleTable.$refs.multipleTable.selection
        .length; //行数也就是人数
      let queryResultArray = this.$refs.multipleTable.list; //

      /**
       * 每点一次平均分配之前，将所有行清空，包括未选中
       */
      for (var i = 0; i < queryResultArray.length; i++) {
        queryResultArray[i].isEnable = "";
      }

      /**
       * 整除，
       * 把每个人的数量（都一样），按照行数从上往下依次赋值
       */
      if (serverOrderNum % userNum == 0) {
        that.usersAndNumber = []; //最新选中   置空
        var averNum = serverOrderNum / userNum; //平均分配数
        //给表格赋值
        for (var i = 0; i < userNum; i++) {
          selectionRowArray[i].isEnable = "";
          selectionRowArray[i].isEnable = averNum;
        }
        //取值组装传给后台
        for (var i = 0; i < userNum; i++) {
          let str =
            selectionRowArray[i].userId + "&" + selectionRowArray[i].isEnable;
          that.usersAndNumber.push(str);
        }
      } else {
        /**
         * 不能整除，
         *1、 线索数 < 人数（余数小于1）
         *2、线索数 > 人数（余数大于1）
         */
        that.usersAndNumber = []; //最新选中   置空
        var averNum = parseInt(serverOrderNum / userNum); //平均分配数
        var lessNum = parseInt(serverOrderNum % userNum); //余数
        if (averNum < 1) {
          //给表格赋值
          for (var i = 0; i < lessNum; i++) {
            selectionRowArray[i].isEnable = "";
            selectionRowArray[i].isEnable = 1;
          }

          //取值组装传给后台
          for (var i = 0; i < lessNum; i++) {
            let str = selectionRowArray[i].userId + "&" + "1";
            that.usersAndNumber.push(str);
          }
        } else {
          /**
           * 先清空表格
           * 给表格赋值
           * 先赋平均值，再从上往下依次加一
           */
          for (var i = 0; i < userNum; i++) {
            selectionRowArray[i].isEnable = "";
            selectionRowArray[i].isEnable = averNum;
          }
          for (var i = 0; i < lessNum; i++) {
            selectionRowArray[i].isEnable++;
          }

          //取值组装传给后台
          for (var i = 0; i < userNum; i++) {
            let str =
              selectionRowArray[i].userId + "&" + selectionRowArray[i].isEnable;
            that.usersAndNumber.push(str);
          }
        }
      }
    },

    /**
     * @clueAssignSure：确认
     * 手工分配
     * 通过把userNumber=[],实现取消电脑分配
     */
    clueAssignSure: function() {
      let that = this;
      let selectionRowArray = this.$refs.multipleTable.$refs.multipleTable.selection; //选择行数组
      let serverOrderNum = that.serverOrderArray.length; //线索单号数量
      /**
       * 计算用户输入线索总数
       */
      let reg = that.$crmcf.crmRegExp("num");
      let userInputClueNum = 0;
      that.usersAndNumber=[]
      for (var i = 0; i < selectionRowArray.length; i++) {
        if(selectionRowArray[i].isEnable!=""&&selectionRowArray[i].isEnable!=null&&selectionRowArray[i].isEnable!="0")
        {
          if(!reg.test(selectionRowArray[i].isEnable))
          {
            this.$message({
              message: "输入格式有误，请重新输入",
              type: "error",
              duration: 1000
            });
            return;
          }
          else{
            userInputClueNum += parseInt(selectionRowArray[i].isEnable);
            let str = selectionRowArray[i].userId + "&" + selectionRowArray[i].isEnable;
            that.usersAndNumber.push(str);
          }
        }
      }
      if (userInputClueNum ==0||that.usersAndNumber.length==0) {
        this.$message({
          message: "请填写要分配的数量",
          type: "error",
          duration: 1000
        });
        return;
      }
      if (userInputClueNum > parseInt(serverOrderNum)) {
        this.$message({
          message: "填写线索数大于选中线索数",
          type: "error",
          duration: 1000
        });
        return;
      }
      
      let queryObj = {
        // api配置
        type: "mutation",
        apiConfig: crmApis.clueServerMutationAssign,
        // 需要调用的API服务配置
        apiServices: [
          {
            //表格中台返回网格的字段
            apiQueryRow: []
          }
        ],
        //条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          dataInfo: {
            assignServerOrders: that.serverOrderArray,
            assignUserIdAndNumber: that.usersAndNumber,
            handleCode: "1"
          }
        }
      };
      //转换了中台请求格式数据
      var paramD = that.$getParams(queryObj);
      // 调用中台API方法（可复用）
      requestGraphQL(paramD).then(response => {
        if (response.data[queryObj.apiConfig.ServiceCode].result == "1") {
          this.$message({
            message: response.data[queryObj.apiConfig.ServiceCode].msg,
            type: "success",
            duration: 1200
          });
          that.curPopupsVisible = false; // 请求成功隐藏
          debugger;
          that.$parent.$refs.multipleTable.query(); //调主页查询
        } else {
          this.$message({
            message: response.data[queryObj.apiConfig.ServiceCode].msg,
            type: "error",
            duration: 1000
          });
        }
      });
    }
  }
};
</script>
